package cn.linjianhui.api.client;

import cn.linjianhui.api.client.exception.RpcClientException;
import cn.linjianhui.api.client.util.CacheUtils;
import cn.linjianhui.api.client.util.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

public class TokenManager {
    private static final String DEFAULT_USER_AGENT = "Rpc-GetUserToken";
    private static final String APP_USER_AGENT = "Rpc-GetAppToken";
    private static final String DEFAULT_CONTENT_TYPE = "application/json;charset=utf-8";
    private static final String LOGIN_URI = "/Auth/Login?user=%s&password=%s";
    private static final String APP_AUTH_URI = "/AppAuth/Login?appkey=%s&appsecret=%s";
    private static CacheUtils<String> userTokenCache = new CacheUtils<>(30);
    private static CacheUtils<String> appTokenCache = new CacheUtils<>(30);

    public static String getTokenByCache(String user, String pwd, String baseUrl) {
        String token = TokenManager.userTokenCache.get(user);
        if(StringUtils.isEmpty(token)) {
            token = TokenManager.getToken(user, pwd, baseUrl);
            TokenManager.userTokenCache.set(user, token);
        }
        return token;
    }

    public static String getAppTokenByCache(String appKey, String appSecret, String baseUrl) {
        String token = TokenManager.appTokenCache.get(appKey);
        if(StringUtils.isEmpty(token)) {
            token = TokenManager.getAppToken(appKey, appSecret, baseUrl);
            TokenManager.appTokenCache.set(appKey, token);
        }
        return token;
    }

    public static String getToken(String user, String pwd, String baseUrl) {
        return request(baseUrl, String.format(LOGIN_URI, user, pwd), DEFAULT_USER_AGENT);
    }

    public static String getAppToken(String appKey, String appSecret, String baseUrl) {
        return request(baseUrl, String.format(APP_AUTH_URI, appKey, appSecret), APP_USER_AGENT);
    }

    private static String request(String baseUrl, String uri, String userAgent) {
        try {
            baseUrl = StringUtils.trimTrailingCharacter(baseUrl, '/');
            HttpGet request = new HttpGet(baseUrl + uri);
            request.addHeader("User-Agent", userAgent);
            request.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
            HttpClient httpClient = HttpUtils.getHttpClient();
            HttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception(String.format("Http status error, status code : %s", statusCode));
            } else {
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity, "UTF-8");
                if (!StringUtils.hasText(content)) {
                    throw new Exception("获取令牌失败");
                }
                return content;
            }
        }catch (Exception e) {
            throw new RpcClientException(e.getMessage());
        }
    }
}
